﻿using LoginModule.DbContexts;
using LoginModule.Models;
using LoginModule.MsgEvents;
using LoginModule.Utils;
using LogModule.Interface;
using LogModule.Interface.Imp;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace LoginModule.ViewModels {
    /// <summary>
    /// 登录视图模型
    /// </summary>
    public class LoginUCViewModel : BindableBase, IDialogAware {

     

        private readonly ILogService _logger;

        private readonly LoginDbContext LoginModuleDbContext;
        public string Title { get; set; } = "生产监控平台";

        //在Prism框架中，RequestClose是IDialogAware接口定义的一个事件，
        //用于​​通知对话框容器关闭当前弹窗​​，并允许传递关闭时的状态和参数

        private readonly IEventAggregator Aggregator;

        /// <summary>
        /// 登录命令
        /// </summary>
        public DelegateCommand LoginCmm { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public LoginUCViewModel(ILogService logger, IEventAggregator _Aggregator, LoginDbContext _LoginModuleDbContext) {
            _logger = logger;
            _logger.Info("登录模块初始化");

            LoginModuleDbContext = _LoginModuleDbContext;
            //登录命令
            LoginCmm = new DelegateCommand(Login);

            //显示注册内容命令
            ShowRegInfoCmm = new DelegateCommand(ShowRegInfo);

            //显示登录内容命令
            ShowLoginInfoCmm = new DelegateCommand(ShowLoginInfo);

            //登录命令
            RegCmm = new DelegateCommand(Reg);

            //实例化注册信息
             AccountInfoDTO = new AccountInfoModel();


            //发布订阅
            Aggregator = _Aggregator;

           
        }

        /// <summary>
        /// 登录方法
        /// </summary>
        private void Login() {
            //数据基本验证
            if (string.IsNullOrEmpty(Account) || string.IsNullOrEmpty(Pwd)) {
                //发布消息
                Aggregator.GetEvent<MsgEvent>().Publish("登录信息不全");
                return;
            }
            if (!LoginModuleDbContext.Database.CanConnect()) {
                _logger.Error("登录模块数据库连接失败");
                throw new InvalidOperationException("数据库连接失败");
            }
            //如果账号密码正确
            //if (Account == "longma" && Pwd == "longma") {
            //    RequestClose.Invoke(new DialogResult(ButtonResult.OK));
            //}
            try {
                Pwd = Md5Hepler.GetMd5(Pwd);
                var TempList = LoginModuleDbContext.AccountInfoModel.Where(x => x.Account == Account).Where(x=>x.Pwd ==Pwd).ToList();
                if (TempList.Count > 0) {
                    AccountInfoModel info = TempList[0];
                    //RequestClose.Invoke(new DialogParameters { { "Account", info.Account }, { "Name", info.Name }, { "Authority", info.Authority } },
                    //   ButtonResult.OK);
                    RequestClose.Invoke(new DialogParameters { { "AccountInfoModel", info }},ButtonResult.OK);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }


        }

        #region 注册
        public DelegateCommand RegCmm { get; set; }

        /// <summary>
        /// 注册
        /// </summary>
        private void Reg() {
            //数据基本验证
            if (string.IsNullOrEmpty(AccountInfoDTO.Name) || string.IsNullOrEmpty(AccountInfoDTO.Account) || string.IsNullOrEmpty(AccountInfoDTO.Pwd) || string.IsNullOrEmpty(AccountInfoDTO.ConfirmPwd)) {
                //发布消息
                Aggregator.GetEvent<MsgEvent>().Publish("注册信息不全");
                //MessageBox.Show("注册信息不全");
                return;
            }

            if (AccountInfoDTO.Pwd != AccountInfoDTO.ConfirmPwd) {
                //发布消息
                MessageBox.Show("两次密码输入不一致");
                _logger.Info("两次密码输入不一致");
                Aggregator.GetEvent<MsgEvent>().Publish("两次密码输入不一致");
                return;
            }
            try {
                if (LoginModuleDbContext.AccountInfoModel.Where(x=>x.Account == AccountInfoDTO.Account).ToList().Count>0) {
                    Aggregator.GetEvent<MsgEvent>().Publish("该账号已存在");
                    _logger.Info("该账号已存在");
                    return;
                }
                var temp = AccountInfoDTO.Pwd;
                AccountInfoDTO.Pwd = Md5Hepler.GetMd5(temp);
                LoginModuleDbContext.AccountInfoModel.AddAsync(AccountInfoDTO);
                LoginModuleDbContext.SaveChangesAsync();
                //发布消息
                Aggregator.GetEvent<MsgEvent>().Publish("注册成功");
                _logger.Info("注册成功");
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }

        }
        #region 注册信息
        /// <summary>
        /// 注册信息
        /// </summary>
        private AccountInfoModel _AccountInfoDTO;

        /// <summary>
        /// 注册信息
        /// </summary>

        public AccountInfoModel AccountInfoDTO {
            get { return _AccountInfoDTO; }
            set {
                _AccountInfoDTO = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #endregion


        #region 显示内容
        /// <summary>
        /// 显示内容的索引
        /// </summary>
        private int _SelectedIndex;

        /// <summary>
        /// 显示内容的索引
        /// </summary>
        public int SelectedIndex {
            get { return _SelectedIndex; }
            set {
                _SelectedIndex = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 显示注册信息命令
        /// </summary>
        public DelegateCommand ShowRegInfoCmm { get; set; }

        /// <summary>
        /// 显示登录信息命令
        /// </summary>
        public DelegateCommand ShowLoginInfoCmm { get; set; }

        /// <summary>
        /// 显示注册信息
        /// </summary>
        private void ShowRegInfo() {
            SelectedIndex = 1;
        }

        /// <summary>
        /// 显示登录信息
        /// </summary>
        private void ShowLoginInfo() {
            SelectedIndex = 0;
        }


        #endregion

        #region 登录信息

        /// <summary>
        /// 账号
        /// </summary>
        private string _Account = "weikai";

        /// <summary>
        /// 账号
        /// </summary>
        public string Account {
            get { return _Account; }
            set {
                _Account = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 密码
        /// </summary>
        private string _Pwd = "weikai";

        /// <summary>
        /// 密码
        /// </summary>
        public string Pwd {
            get { return _Pwd; }
            set {
                _Pwd = value;
                RaisePropertyChanged();
            }
        }
        #region IDialogAware接口方法
        /// <summary>
        /// 
        /// </summary>
        //DialogCloseListener IDialogAware.RequestClose => throw new NotImplementedException();
        public DialogCloseListener RequestClose { get; }
        /// <summary>
        /// 是否能够关闭对话框,就是在关闭对话框的时候调用1
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        bool IDialogAware.CanCloseDialog() {
            return true;
        }
        /// <summary>
        /// 关闭,就是在关闭对话框的时候调用2
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        void IDialogAware.OnDialogClosed() {

            //todo 如何判空啊
            //RequestClose.Invoke(new DialogResult(ButtonResult.No));

        }
        /// <summary>
        /// 打开对话框,就是在打开对话框的时候调用,传递参数
        /// </summary>
        /// <param name="parameters">接收数据,通过key值</param>
        /// <exception cref="NotImplementedException"></exception>
        void IDialogAware.OnDialogOpened(IDialogParameters parameters) {

        }
        #endregion

        #endregion
    }
}
